package offer.offer04;

import java.math.BigInteger;

/**
 * 6, 5 没事……好歹写出来了……
 */
public class Solution67_3 {
    public int strToInt(String str) {
        String str2 = str.trim();//消除首尾空格, 尾去不去掉无所谓
        StringBuilder strBuilder = new StringBuilder(str2);
        StringBuilder resultBuilder = new StringBuilder("");
        int flag = 1;
        //对于第一个, 判断一下符号
        if(strBuilder.length() != 0 && (strBuilder.charAt(0) == '+' || strBuilder.charAt(0) == '-')){
            flag = strBuilder.charAt(0) == '+'? 1: -1;
            strBuilder.deleteCharAt(0);
        }
        //后面的要是数字才收
        for(int i = 0; i < strBuilder.length(); i++){
            char c = strBuilder.charAt(i);
            if(!Character.isDigit(c)) break;
            resultBuilder.append(c);
        }

        int resultInt = 0;
        if(resultBuilder.length() != 0){
            BigInteger resultBig = new BigInteger(resultBuilder.toString());
            System.out.println("结果的数字部分为: " + resultBig);
            if(flag == 1 && resultBig.compareTo(new BigInteger("" + Integer.MAX_VALUE)) == 1){
                resultBig = new BigInteger("" + Integer.MAX_VALUE);
            }else {
                if(flag == -1 && resultBig.compareTo(new BigInteger("2147483648")) == 1){
                    resultBig = new BigInteger("" + Math.abs(Integer.MIN_VALUE));
                }
            }
            resultInt = resultBig.intValue();
        }
        return flag*resultInt;
    }

    public int strToInt2(String str) {
        char[] c = str.trim().toCharArray();//看, 还有这招……
        if(c.length == 0) return 0;
        int res = 0, bndry = Integer.MAX_VALUE / 10;
        int i = 1, sign = 1;
        if(c[0] == '-') sign = -1;
        else if(c[0] != '+') i = 0;
        for(int j = i; j < c.length; j++) {
            if(c[j] < '0' || c[j] > '9') break;
            //就MAX_VALUE和MIN_VALUE之间并不是正负关系, 但是光用这个 > '7'也能正确判断, 而不用对末尾的7和8做区分
            if(res > bndry || res == bndry && c[j] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = res * 10 + (c[j] - '0');
        }
        return sign * res;
    }


    public static void main(String[] args) {
        String input = " +434364889765542346 sdfygfg sdfr -434364889765542346 5437984573468756 876 097096";
        System.out.println("输出结果为: " + new Solution67_3().strToInt(input));
    }
}
